#include "MiniMeshHandler.h"

MiniMeshHandler::MiniMeshHandler(MiniObject *obj) : MiniHandler(obj)
{
    // 检查是否有法向，如果没有，就插值出法向
    MiniMesh *mesh = (MiniMesh*)obj;
    if (!mesh->HasVertexNormal())
        for (int i = 0; i < mesh->VertexNum(); i++)
            mesh->m_nList.push_back(mesh->Gouraud(mesh->m_vList[i]));

    UpdateHandler();
}

float MiniMeshHandler::CheckCollision(QPointF pos, QMatrix4x4 projection)
{
    // 网格暂时不处理碰撞
    Q_UNUSED(pos)
    Q_UNUSED(projection)
    return 1;
}

void MiniMeshHandler::ChangeVertex(Vector3f dv)
{
    // 网格不支持局部修改点
    Q_UNUSED(dv)
}

void MiniMeshHandler::UpdateHandler()
{
    InitHandler();

    // 转化为网格类型
    MiniMesh *mesh = (MiniMesh*)m_object;

    int n = mesh->VertexNum();
    int m = mesh->FaceNum();

    // 注意这里要考虑面的顶点数
    float* vertices = new float[n*6];
    unsigned int* indices = new unsigned int[m*3];

    // 按顺序标记顶点
    for (int i = 0; i < n; i++)
        mesh->m_vList[i]->identity = i;

    // 输出所有顶点和法向信息
    for (int i = 0; i < n; i++)
    {
        vertices[6 * i + 0] = mesh->m_vList[i]->pos.x();
        vertices[6 * i + 1] = mesh->m_vList[i]->pos.y();
        vertices[6 * i + 2] = mesh->m_vList[i]->pos.z();
        vertices[6 * i + 3] = mesh->m_nList[i].x();
        vertices[6 * i + 4] = mesh->m_nList[i].y();
        vertices[6 * i + 5] = mesh->m_nList[i].z();
    }

    // 遍历网格面，记录顶点索引
    int index = 0;
    for (int i = 0; i < m; i++)
    {
        std::deque<vertex3f *> v = mesh->VertexOnFace(mesh->m_fList[i]);
        for (int j = 0; j < v.size(); j++)
            indices[index++] = v[j]->identity;
    }

    // 储存数据
    m_countIndices.push_back(m*3);
    m_countVertices.push_back(n*2);
    m_vertices.push_back(vertices);
    m_indices.push_back(indices);
    m_modes.push_back(GL_TRIANGLES);
    m_color.push_back(m_basisColor);
}
